/**
 * 
 */
package com.apchernykh.player;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.apchernykh.rozhlasapp.utils.ConditionalLog;

import android.os.Environment;

public class Logger {
	private PrintWriter mWriter = null;
	public boolean mIsLogOpened = false;
	public String mLoggerFileName = "com.apchernykh.default.log";
	private final static DateFormat mDateFormat = new SimpleDateFormat("[yyyy/MM/dd HH:mm:ss]", Locale.US);
	private final static String[][] mDeviceInfo =  new String[][]{{"Brand", android.os.Build.BRAND}, {"Device", android.os.Build.DEVICE}, {"Display", android.os.Build.DISPLAY}, {"Id", android.os.Build.ID}, {"Model", android.os.Build.MODEL}};

	public void close() {
		try {
			if (!mIsLogOpened)
				return;
			if (mWriter != null) {
				mWriter.close();
			}
			mIsLogOpened = false;
		} catch (Throwable e) {
			ConditionalLog.e(this.toString(),
					"Unable to close log file.", e);
		}
	}

	
	public void warn(String iMessage) {
		try {
			if (mIsLogOpened) {
				Date aDate = new Date();
				mWriter.println(mDateFormat.format(aDate).concat(iMessage));
				mWriter.flush();
			}
		} catch (Throwable e) {
			ConditionalLog.e(this.toString(),
					"Unable to write to log file. Closed log", e);
		}
	}

	public void open() {
		if (mIsLogOpened) {
			return;
		}
		try {
			File aOutFile = new File(Environment.getExternalStorageDirectory(),
					mLoggerFileName);
			FileOutputStream aOutputStream = new FileOutputStream(aOutFile, true);
			mWriter = new PrintWriter(aOutputStream);
			mIsLogOpened = true;
			warn("Started logging, "+getDeviceInfo());
		} catch (Throwable e) {
			ConditionalLog.e(this.toString(), "Unable to open log file", e);
			mIsLogOpened = false;
			mWriter = null;
		}
	}
	
	private String getDeviceInfo() {
		String aDeviceInfoString = "";
		for(String[] pair: mDeviceInfo)
		{
			for(String item: pair)
			{
				aDeviceInfoString=aDeviceInfoString+" "+item;
			}
			aDeviceInfoString = aDeviceInfoString+";";
		}
		return aDeviceInfoString;
	}
}